//
//  MHTable+Insert.m
//  数据库的读写封装
//
//  Created by zsgjs on 2017/2/21.
//  Copyright © 2017年 zsgjs. All rights reserved.
//

#import "MHTable+Insert.h"
#import "FMDB.h"

@implementation MHTable (Insert)

- (void)insertFields:(NSDictionary *)fields
{
    [self.db clean];
    [self.db setCurrentTableName:self.tableName];
    [self.db insertData:fields];
    
//    NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO %@(id,colunms,colunms1) values(?,?,?);", self.db.currentTableName];
//    NSData *saveData = [NSKeyedArchiver archivedDataWithRootObject:fields];
//    
//    __block bool result;
//    [self.db.queue inDatabase:^(FMDatabase *db) {
//        result = [db executeUpdate:insertSQL, @1, @"234", saveData];
//    }];
    
}

- (void)insertColumnIfNotExist:(NSString *)column type:(NSString *)type
{
    NSDictionary *dict = @{column : @""};
    if (![self hasFields:dict]) {
        [self.db insertNewColumn:column type:type];
    }
}

- (void)insertFields:(NSDictionary *)fields andWhere:(NSString *)where
{
    if (![self hasWhere:where]) {
        [self insertFields:fields];
    }
//    ? [self updateFields:fields andWhere:where]:
}

- (void)insertNewColsWithNames:(NSArray *)colsNames types:(NSArray *)types
{
    [colsNames enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx > types.count - 1) {
            NSException *excp = [NSException exceptionWithName:@"please check columns name and types"
                                                        reason:@"columns and types must be equaled"
                                                      userInfo:@{@"colums": @(colsNames.count),
                                                                 @"types": @(types.count)}];
            @throw excp;
        }
        [self insertColumnIfNotExist:obj type:types[idx]];
    }];
}

@end
